#include "libutilsconfig.h"
#include "StringBuilder.h"

LIB_NS_BEGIN

static const int DEFAULT_BUFF_LEN = 512;
StringBuilder::StringBuilder(size_t capi)
{
	_init(capi);
}

void StringBuilder::_init(int32 cap)
{
	_bufflen = cap;
	_buff = new TCHAR[_bufflen+1];
	_pos = 0;
	_buff[_pos]=0;
}

StringBuilder::StringBuilder()
{
	_init(DEFAULT_BUFF_LEN);
}

StringBuilder::~StringBuilder(void)
{
	delete[] _buff;
}

void StringBuilder::_resize(int32 newlen)
{
	
	TCHAR* newbuff = new TCHAR[newlen+1];
	_tcscpy(newbuff,_buff);
	delete _buff;
	_buff = newbuff;
	_bufflen = newlen;
}

void StringBuilder::Append( TCHAR value )
{
	TCHAR data[2] = {value,0};
	Append(data);
}

void StringBuilder::Append( const TCHAR* value )
{
	int32 len = _tcslen(value);
	if(len+_pos <= _bufflen)
	{
		_tcscat(_buff,value);
		_pos += len;
	}
	else
	{
		int newlen = (len + _pos)*2;
		_resize(newlen);
		Append(value);
	}
}

void StringBuilder::Append( const tstring& value )
{
	return Append(value.c_str());
}

void StringBuilder::_appendend()
{
	_buff[_pos]=0;
}

tstring StringBuilder::ToString()
{
	return _buff;
}
LIB_NS_END